import {Injectable} from "injection-js";
import {Mut, VueService} from "vue3-oop";
import {NButton, NSpace} from "naive-ui";
import RoleApi from "../../RoleApi";
import SelectDialog from "@/components/tool/SelectDialog";

@Injectable()
export default class AllcPrmsSercice extends VueService {

  constructor(
  ){
    super();
  }

  @Mut() state = {
    roleId:"",
    roleName:""
  }

  init=(roleId:string,roleName:string)=>{
    this.state.roleId = roleId;
    this.state.roleName = roleName;
    this.searchData("");
  }

  @Mut() pagination={
    showSizePicker: true,
    showQuickJumper: true,
    pageSizes: [10,20,50,100],
    pageSize: 10,
    page: 1,
    itemCount: 0,
  }

  /**
   * 查询分配给角色的权限
   * @param value 快速搜索框输入值
   */
  searchData=(value:string)=>{
    if(this.state.roleId.length>0){
      RoleApi.prmsPage({
        params:{
          roleId: this.state.roleId
        },
        page:{size: this.pagination.pageSize, current: this.pagination.page}
      }).then(({data})=>{
        if(data.success&&data.record){
          this.panelProps.nDataTableProps.data = data.record
        }
      })
    }
  }

  @Mut() panelProps = {
    name: "权限分配",
    code: "prms_alloc",
    default: true,
    showSearchBar: true,
    showSearchExt: true,
    toolbarActions: [
      {
        name:"分配",
        needCheck:false,
        inMore:false,
        onClick:()=>{
          this.openAllocateDialog(this.state.roleId,this.state.roleName);
        }
      }
    ],
    onQuickSearch: this.searchData,
    nDataTableProps: {
      columns: [
        {
          key: "prmsName",
          title: "权限名"
        },{
          key: "prmsCode",
          title: "编码"
        },{
          key: "disabled",
          title: "禁用",
          render: (row:any)=>(row['disabled']===true?"是":"否")
        },{
          key: "SYS_ROW_ACTIONS",
          title: "操作",
          render: (row:any)=>(<NSpace size="small">
            <NButton onClick={()=>{this.disable(row)}}>{row['disabled']===true?"启用":"禁用"}</NButton>
            <NButton onClick={()=>{this.regain(row)}}>收回</NButton>
          </NSpace>)
        }
      ],
      data: [],
      pagination: this.pagination
    },
    onMounted:()=>{
      this.searchData("")
    }
  }

  /**
   * 收回权限
   */
  regain=(row:any)=>{
    RoleApi.prmsRegain({
      params:{id:[row.id]}
    }).then(({data})=>{
      if(data.success){
        window.$message.success("权限收回成功");
        this.searchData("");
      }
    })
  }

  /**
   * 禁用权限
   */
  disable=(row:any)=>{
    RoleApi.prmsDisable({
      params:{disabled:!row['disabled'],id:[row.id]}
    }).then(({data})=>{
      if(data.success){
        window.$message.success(data.message);
        this.searchData("");
      }
    })
  }

  // 打开选择权限进行分配的弹窗
  private openAllocateDialog=(roleId:string,roleName:string)=>{
    const selectDialog = new SelectDialog({
      title: `为角色“${roleName}”分配权限`,
      multiple: true,
      rowKey: "id",
      columns: [{key: "name", title: "权限名"},{key: "code", title: "编码"}],
    });

    // 查询可分配的权限
    const searchAvailable=()=>{
      return new Promise((resolve, reject)=>{
        RoleApi.prmsAvailable({
          params:{
            _search: selectDialog.getSearchValue(),
            roleId: this.state.roleId
          },
          page:{
            size: selectDialog.getPageSize(),
            current: selectDialog.getPage()
          }
        }).then(({data})=>{
          if(data.success){
            selectDialog.setData(data.record);
            selectDialog.setItemCount(data.page.total);
            resolve(data);
          }else{
            reject(data);
          }
        })
      });
    }

    // 搜索方法
    const onSearch=(value:string|undefined)=>{
      selectDialog.setPage(1);
      selectDialog.setData([]);
      searchAvailable();
    }

    searchAvailable().then(()=>{
      selectDialog.setOnSearch(onSearch);
      selectDialog.setOnConfirm(this.onConfirm)
      selectDialog.setOnUpdatePage((newPage)=>{
        selectDialog.setPage(newPage);
        searchAvailable();
      });
      selectDialog.open();
    });
  }

  // 选择数据确认后的回调
  private onConfirm=(keys:any[])=>{
    RoleApi.prmsAllocate({
      params:{
        roleId:this.state.roleId,
        prmsId:keys
      }
    }).then(({data})=>{
      if(data.success){
        window.$message.success("分配权限成功")
      }
      this.searchData("");
    })
  }
}